<script setup>
import { ref, onMounted, watch } from 'vue'
import { studentService } from '../../services/student'
import courseService from '../../services/course'  // 修改这行
import DataTable from '../../components/common/DataTable.vue'
import SearchBar from '../../components/studentlist/SearchBar.vue'
import { showSuccess, showError, showWarning } from '../../utils/message'  // 修改这行
import CourseAssignDialog from '../../components/course/CourseAssignDialog.vue'
import CourseViewDialog from '../../components/course/CourseViewDialog.vue'
import { useStudentStore } from '../../stores/student'  // 添加这行

// 添加 store
const studentStore = useStudentStore()

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const columns = [
  { prop: 'account', label: '账号', width: '120', align: 'center' },
  { prop: 'name', label: '姓名', width: '100', align: 'center' },
  { prop: 'phone', label: '手机号', width: '120', align: 'center' },
  { prop: 'school', label: '学校', align: 'center' },
  { prop: 'class', label: '班级', width: '120', align: 'center' },
  { prop: 'teacher', label: '老师', width: '100', align: 'center' },
  { 
    prop: 'isTrialAccount',
    label: '试用账号',
    width: '100',
    align: 'center',
    formatter: (row) => row.isTrialAccount ? '是' : '否'
  },
  {
    slot: 'actions',
    label: '操作',
    align: 'center',
    fixed: 'right'
  }
]

// 加载学生数据
const loadStudents = async (searchParams = {}) => {
  try {
    loading.value = true
    const { data, total } = await studentService.getStudentsForCourse({
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      filters: searchParams
    })
    tableData.value = data
    pagination.value.total = total
  } catch (error) {
    showError('加载学生数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 添加对话框引用
const courseAssignDialogRef = ref(null)
const courseViewDialogRef = ref(null)

// 处理表格操作
const handleTableAction = async ({ action, row }) => {
  try {
    switch (action) {
      case 'view':
        studentStore.setCurrentStudent(row)
        courseViewDialogRef.value?.openDialog()
        break
      case 'assign':
        studentStore.setCurrentStudent(row)  // 添加这行
        courseAssignDialogRef.value?.openDialog()
        break
    }
  } catch (error) {
    showError('操作失败')
    console.error(error)
  }
}

// 添加 selection 相关逻辑
const selectedStudents = ref([])

const handleSelectionChange = (selection) => {
  selectedStudents.value = selection
  studentStore.setSelectedStudents(selection)
}

// 添加批量操作按钮处理
const handleBatchAssign = () => {
  if (!selectedStudents.value.length) {
    showWarning('请选择要分配课程的学生')
    return
  }
  courseAssignDialogRef.value?.openDialog()
}

// 修改处理分发确认
const handleCourseAssign = async (data) => {
  try {
    if (data.studentIds) {
      // 批量分发
      for (const studentId of data.studentIds) {
        await courseService.assignCoursesToStudent(studentId, data.courses)
      }
    } else {
      // 单个分发
      await courseService.assignCoursesToStudent(data.studentId, data.courses)
    }
    
    showSuccess('课程分发成功')
    studentStore.clearSelection()
    selectedStudents.value = []
    await loadStudents()
  } catch (error) {
    if (error.message === '该学生已分配了部分课程，请勿重复分配') {
      showError(error.message)
    } else {
      showError('课程分发失败，请稍后重试')
    }
    console.error(error)
  }
}

// 处理搜索
const handleSearch = async (params) => {
  pagination.value.currentPage = 1
  await loadStudents(params)
}

// 监听分页变化
watch(
  () => [pagination.value.currentPage, pagination.value.pageSize],
  () => loadStudents()
)

onMounted(() => {
  loadStudents()
})

const handleViewDialogClose = () => {
  studentStore.clearCurrentStudent()
}
</script>

<template>
  <div class="course-assign">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <div class="batch-actions" v-if="selectedStudents.length">
            <el-button type="primary" @click="handleBatchAssign">
              统一分发课程
            </el-button>
          </div>
          <span v-else>课程分配</span>
        </div>
      </template>
      
      <search-bar @search="handleSearch" />
      
      <!-- 修改 data-table，添加 selection 支持 -->
      <data-table
        v-loading="loading"
        :data="tableData"
        :columns="columns"
        v-model:pagination="pagination"
        @action="handleTableAction"
        @selection-change="handleSelectionChange"
      >
        <template #actions="{ row }">
          <el-button link type="primary" @click="handleTableAction({ action: 'view', row })">
            查看
          </el-button>
          <el-button link type="primary" @click="handleTableAction({ action: 'assign', row })">
            分发
          </el-button>
        </template>
      </data-table>
    </el-card>
  </div>
  <course-assign-dialog
    ref="courseAssignDialogRef"
    :student="studentStore.currentStudent"
    :selected-students="selectedStudents"
    @confirm="handleCourseAssign"
  />
  <course-view-dialog
    ref="courseViewDialogRef"
    :student="studentStore.currentStudent"
    @closed="handleViewDialogClose"
  />
</template>

<style scoped>
.page-card {
  margin: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
